package com.hualian.coupon.controller;

import com.hualian.coupon.exception.BusinessException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 毕磊
 * @version 1.0
 * @date 2020/10/20 0020 9:55
 */

@RestController
@RequestMapping("/upload")
public class UploadController {


    @PostMapping("/img")
    public Map<String,String> upload(MultipartFile file) throws IOException {

        // abc.png
        String originalFilename = file.getOriginalFilename();

        // 后缀必须是: png / jpg/ jpeg /gif
        // substring(lastIndexOf(".")+1)
        if (originalFilename == null) {
            throw new BusinessException("文件名不能为空");
        }
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName = UUID.randomUUID().toString();
        fileName = fileName.replaceAll("-","");

        // 通过uuid生成文件名+原后缀-> 组成新的文件名 : dest
        String dest = "/usr/upload/img/"+fileName+suffix;



        file.transferTo(new File(dest));

        Map<String, String> map = new HashMap<>(8);
        map.put("fileName", fileName);
        //返回给前端

        return map;
    }
}
